<?php
include("config.php");
/*if (isset($_POST["args2"])) {
  print_r($_POST["args2"]);
  exit;
}*/
global $universe;

if (isset($_GET["universe"])) {
  // TODO: check for referrer to disable universe to universe modification
  // echo $_SERVER['HTTP_REFERER'];
  $universe = $_GET["universe"];
} else {
  echo "No universe defined";
  exit;
}

$con = mysql_connect(
  $config->mysql_host, 
  $config->mysql_username, 
  $config->mysql_password);

mysql_select_db($config->mysql_database);

function validate_sql($query) {
  global $universe;
  $valid_command = Array(
      "INSERT INTO ",
      "UPDATE ",
      "SELECT ",
      "DELETE FROM ",
      "DROP TABLE ",
      "CREATE TABLE ",
    );
  $command = "";
  foreach($valid_command as $valid) {
    if (substr(strtoupper($query), 0, strlen($valid)) == $valid) {
      $command = $valid;
      if ($command == "SELECT ") {
        $query = preg_replace("/FROM |from /", "FROM ".$universe."_", $query);
      } else {
        $query = $command.$universe."_".trim(substr($query, strlen($valid)));
      }
    }
  }
  if (!$command) {
    echo $query. " did not pass validation";
    exit;
  }
  return $query;
}

if ($_GET["sql"]) {
  $res = mysql_query(validate_sql($_GET["sql"]));
  if (!$res) {
    header("Status: 400 Bad Request");
    echo "Mysql error \n";
    echo mysql_errno($con) . ": " . mysql_error($con) . " \nQuery: ".$query;
    exit;
  }
  $arr = mysql_fetch_array($res);
  echo $arr[0];
  exit;
}

if ($_POST["sql"]) {
  $query = validate_sql($_POST["sql"]);
  
  if ($_POST["args"]) {
    $args = json_decode($_POST["args"]);
    
    $escaped_args = Array();
    foreach($args as $arg) {
      $escaped_args[] = mysql_real_escape_string($arg);
    }
    $query = vsprintf($query, $escaped_args);
  }
  $res = mysql_query($query, $con);
  if (!$res) {
    header("Status: 400 Bad Request");
    echo "Mysql error \n";
    echo mysql_errno($con) . ": " . mysql_error($con) . " \nQuery: ".$query;
    exit;
  }
  
  if (substr(strtoupper($query), 0, strlen("SELECT ")) == "SELECT ") {
    while($result = mysql_fetch_assoc($res)) {
      $ret[] = $result;
    }
    echo json_encode($ret);
    exit;
  }
  exit;
}
  
$result = mysql_fetch_assoc(mysql_query("SELECT source FROM ".$universe."_world"));
echo $result["source"];
?>
